package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.feign.client.ItemClient;
import com.hmall.order.constant.OrderMQConstant;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听订单失效
 */
@Component
@Slf4j
public class OrderListener {
    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private ItemClient itemClient;

    /**
     * 监听回调
     *
     * @param orderId 订单号
     */
    @RabbitListener(queues = OrderMQConstant.DEAD_LETTER_QUEUE)
    public void handleOrderMsg(String orderId) {
        log.info("=============== 处理失效订单 start ===============");

        //判断该订单是否已经支付，如果还是未支付，才进行修改（关闭订单，库存还原）
        Order order = orderMapper.selectById(orderId);
        //查询不到，不处理
        if (order == null) {
            return;
        }
        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().eq("order_id", order.getId()));
        if (orderDetail == null) {
            return;
        }
        //订单的状态，1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束，已评价
        if (order.getStatus() == 1) {
            //关闭订单
            order.setStatus(5);
            orderMapper.updateById(order);
            //归还库存
            returnItemStockNum(orderDetail.getItemId(), orderDetail.getNum());
            log.info("=============== 处理失效订单 成功！ ===============");
        }

        log.info("=============== 处理失效订单 end ===============");
    }

    /**
     * 归还商品的库存
     *
     * @param itemId 商品Id
     * @param num    要归还的库存数量
     */
    private void returnItemStockNum(Long itemId, Integer num) {
        // 通过Feign远程调用商品服务，增加库存
        itemClient.returnItemStockNum(itemId, num);
        log.info("订单微服务，归还库存，商品Id => " + itemId + "，归还数量：" + num);
    }
}